package com.example.sunmiv1.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.GoodBean;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.VipListBean;
import com.example.sunmiv1.utils.MathUtil;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.printUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MemberLoginActivity extends Activity {

    @BindView(R.id.memberLogin_cardNum)
    TextView memberLoginCardNum;
    @BindView(R.id.memberLogin_name)
    TextView memberLoginName;
    @BindView(R.id.memberLogin_grade)
    TextView memberLoginGrade;
    @BindView(R.id.memberLogin_integral)
    TextView memberLoginIntegral;
    @BindView(R.id.memberLogin_money)
    TextView memberLoginMoney;
    @BindView(R.id.memberLogin_allPrice)
    TextView memberLoginAllPrice;
    @BindView(R.id.memberLogin_zheKou)
    TextView memberLoginZheKou;
    @BindView(R.id.memberLogin_realPay)
    TextView memberLoginRealPay;
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.memberLogin_sure)
    TextView memberLoginSure;
    @BindView(R.id.vipLogin_close)
    ImageView vipLoginClose;
    @BindView(R.id.vipLogin_pass)
    EditText vipLoginPass;
    @BindView(R.id.vipLogin_sure)
    TextView vipLoginSure;
    @BindView(R.id.vipLogin_linear)
    LinearLayout vipLoginLinear;
    @BindView(R.id.memberLogin_coupon)
    TextView memberLoginCoupon;

    private String vipId;
    private double allPrice = 0;
    private double integralDiscount = 0;
    private double discountMoney = 0;
    private double couponMoney = 0;
    private double zheKou = 0;
    private double realPay = 0;
    private ACache aCache;
    private Context context;
    private LoadingDialog loadingDialog;
    private List<GoodBean.DataBean.GoodsBean> list;
    private Intent intent;
    private LoginEntity LoginEntity;
    //    private VipListBean vipinfoBean;
    private VipListBean.InfoBean infoBean;
    private double discount;
    private String payCode = "";
    private int Login_type = 0;
    private static final String TAG = "MemberLoginActivity";
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loadingDialog.dismiss();
                    allPrice = 0;//商品總金額
                    integralDiscount = 0;//會員積分抵扣
//                    infoBean = vipinfoBean.getInfo().get(0);
                    for (int i = 0; i < list.size(); i++) {
                        double price = 0;
                        double temp_price = 0;
                        if ("2".equals(infoBean.getPlus_type())) { //plus會員
                            if ("1".equals(list.get(i).getPlus_mem_status())) { //開啓門店plus會員價
                                if ("2".equals(list.get(i).getAttribute_state()) && list.get(i).getSkujson() != null && list.get(i).getSkujson().size() > 0) { //判斷規格商品
                                    price = Double.parseDouble(list.get(i).getSkujson().get(0).getPlus_price());
                                    temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getSkujson().get(0).getRetail_price()), price);
                                    temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                } else {
                                    price = Double.parseDouble(list.get(i).getPlus_price());
                                    temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), price);
                                    temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                }
                            } else { //未開啓門店plus會員價
                                if ("1".equals(list.get(i).getStore_mem_status())) { //開啓門店會員價
                                    if ("2".equals(list.get(i).getAttribute_state()) &&
                                            list.get(i).getSkujson() != null &&
                                            list.get(i).getSkujson().size() > 0) {
                                        if ("2".equals(list.get(i).getSkujson().get(0).getStore_mem_status())) {
                                            price = Double.parseDouble(list.get(i).getRetail_price());
                                            if (price < 0.01) {
                                                price = 0.01;
                                            }
                                            temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), price);
                                            temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                        } else {
                                            if (list.get(i).getStore_mem_price() != null) {
                                                price = Double.parseDouble(list.get(i).getSkujson().get(0).getStore_mem_price());
                                                if (price < 0.01) {
                                                    price = 0.01;
                                                }
                                                double allPrice = MathUtil.mul(price, list.get(i).getAgoods_count());
                                                temp_price = MathUtil.sub(MathUtil.mul(Double.parseDouble(list.get(i).getSkujson().get(0).getRetail_price()),
                                                        list.get(i).getAgoods_count()), allPrice);
                                            } else {
                                                price = Double.parseDouble(list.get(i).getRetail_price());
                                                if (price < 0.01) {
                                                    price = 0.01;
                                                }
                                                temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), price);
                                                temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                            }
                                        }
                                    } else {
                                        if ("2".equals(list.get(i).getStore_mem_status())) {
                                            price = Double.parseDouble(list.get(i).getRetail_price());
                                            temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), price);
                                            temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                        } else {
                                            if (list.get(i).getStore_mem_price() != null) {
                                                if (!list.get(i).getStore_mem_price().equals("")) {
                                                    price = Double.parseDouble(list.get(i).getStore_mem_price());
                                                } else {
                                                    price = Double.parseDouble(list.get(i).getRetail_price());
                                                }
                                                if (price < 0.01) {
                                                    price = 0.01;
                                                }
                                                double allPrice = MathUtil.mul(Double.parseDouble(list.get(i).getStore_mem_price()),
                                                        list.get(i).getAgoods_count());
                                                temp_price = MathUtil.sub(MathUtil.mul(Double.parseDouble(list.get(i).getRetail_price()),
                                                        list.get(i).getAgoods_count()), allPrice);
                                            } else {
                                                price = Double.parseDouble(list.get(i).getRetail_price());
                                                if (price < 0.01) {
                                                    price = 0.01;
                                                }
                                                temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), price);
                                                temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                            }
                                        }
                                    }
                                } else {
                                    price = Double.parseDouble(list.get(i).getRetail_price());
                                    temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), price);
                                    temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                }
                            }
                            price = MathUtil.round(price, 2);
                            Log.e(TAG, "dazhe: temp_price=" + temp_price);
                            temp_price = MathUtil.round(temp_price, 2);
                            discountMoney += temp_price;
                            price = MathUtil.mul(price, list.get(i).getAgoods_count());
                        } else { //常規會員
                            if ("2".equals(list.get(i).getAttribute_state()) && list.get(i).getSkujson() != null && list.get(i).getSkujson().size() > 0) {
                                if ("2".equals(list.get(i).getSkujson().get(0).getStore_mem_status())) {
                                    price = MathUtil.mul(Double.parseDouble(list.get(i).getRetail_price()), list.get(i).getAgoods_count());
                                    if (price < 0.01) {
                                        price = 0.01;
                                    }
                                    temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), Double.parseDouble(list.get(i).getRetail_price()));
                                    temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                } else {
                                    if (list.get(i).getStore_mem_price() != null) {
                                        price = MathUtil.mul(Double.parseDouble(list.get(i).getSkujson().get(0).getStore_mem_price()), list.get(i).getAgoods_count());
                                        if (price < 0.01) {
                                            price = 0.01;
                                        }
                                        double allPrice = MathUtil.mul(Double.parseDouble(list.get(i).getSkujson().get(0).getStore_mem_price()),
                                                list.get(i).getAgoods_count());
                                        temp_price = MathUtil.sub(MathUtil.mul(Double.parseDouble(list.get(i).getSkujson().get(0).getRetail_price()),
                                                list.get(i).getAgoods_count()), allPrice);
                                    } else {
                                        price = MathUtil.mul(Double.parseDouble(list.get(i).getRetail_price()), list.get(i).getAgoods_count());
                                        if (price < 0.01) {
                                            price = 0.01;
                                        }
                                        temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), Double.parseDouble(list.get(i).getRetail_price()));
                                        temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                    }
                                }
                            } else {
                                if ("2".equals(list.get(i).getStore_mem_status())) {
                                    price = MathUtil.mul(Double.parseDouble(list.get(i).getRetail_price()), list.get(i).getAgoods_count());
                                    if (price < 0.01) {
                                        price = 0.01;
                                    }
                                    temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), Double.parseDouble(list.get(i).getRetail_price()));
                                    temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                } else {
                                    if (list.get(i).getStore_mem_price() != null) {
                                        price = MathUtil.mul(Double.parseDouble(list.get(i).getStore_mem_price()), list.get(i).getAgoods_count());
                                        if (price < 0.01) {
                                            price = 0.01;
                                        }
                                        double allPrice = MathUtil.mul(Double.parseDouble(list.get(i).getStore_mem_price()),
                                                list.get(i).getAgoods_count());
                                        temp_price = MathUtil.sub(MathUtil.mul(Double.parseDouble(list.get(i).getRetail_price()),
                                                list.get(i).getAgoods_count()), allPrice);
                                    } else {
                                        price = MathUtil.mul(Double.parseDouble(list.get(i).getRetail_price()), list.get(i).getAgoods_count());
                                        if (price < 0.01) {
                                            price = 0.01;
                                        }
                                        temp_price = MathUtil.sub(Double.parseDouble(list.get(i).getRetail_price()), Double.parseDouble(list.get(i).getRetail_price()));
                                        temp_price = MathUtil.mul(temp_price, list.get(i).getAgoods_count());
                                    }
                                }
                            }
                        }
                        temp_price = MathUtil.round(temp_price, 2);
                        discountMoney += temp_price;
                        allPrice += MathUtil.round(price, 2);
                    }
                    allPrice = allPrice - couponMoney;
                    //積分優惠
                    if (infoBean == null) {
                    } else {
//            if (LoginEntity.getData().getMerchantConfig().getIntegral_arrive_cash().equals("1")) {
//                llIntegral.setVisibility(View.VISIBLE);
//            } else {
//                llIntegral.setVisibility(View.GONE);
//            }
                        double integralMoney = 0.00, needIntegral = 0.00;
                        LoginEntity = GsonUtils.JsonToBean(aCache.getAsString("LoginInfo"), LoginEntity.class);
                        if (LoginEntity.getData().getMerchantConfig().getIntegral_arrive_cash().equals("1")) {
                            integralMoney = MathUtil.mul(allPrice, Double.parseDouble(LoginEntity.getData().getMerchantConfig().getIntegral_arrive_cash_rate()));
                            needIntegral = MathUtil.mul(integralMoney, 100, Double.parseDouble(LoginEntity.getData().getMerchantConfig().getIntegral_arrive_cash_data()));
                            if (Double.parseDouble(infoBean.getIntegral()) > needIntegral) {
                                allPrice = allPrice - integralMoney;
                                integralDiscount = integralMoney;
                            } else {
                                double discountMoney = MathUtil.mul(MathUtil.div(Double.parseDouble(infoBean.getIntegral()),
                                        Double.parseDouble(LoginEntity.getData().getMerchantConfig().getIntegral_arrive_cash_data()), 2), 0.01);
                                allPrice = allPrice - discountMoney;
                                integralDiscount = discountMoney;
                            }
                        }
                    }
                    allPrice = MathUtil.round(allPrice, 2);
                    if (list.size() > 0 && allPrice <= 0) {
                        allPrice = 0.01;
                    }
                    allPrice = Double.parseDouble(decimalFormat.format(allPrice));
                    vipId = infoBean.getId();
                    memberLoginCardNum.setText(context.getResources().getString(R.string.memberLogin_cardNum) + infoBean.getPayCode());
                    if (infoBean.getNickname() != null) {
                        memberLoginName.setText(context.getResources().getString(R.string.memberLogin_name) + infoBean.getNickname());
                    } else {
                        if (infoBean.getName() != null) {
                            memberLoginName.setText(context.getResources().getString(R.string.memberLogin_name) + infoBean.getName());
                        } else {
                            memberLoginName.setText(context.getResources().getString(R.string.memberLogin_name) + getString(R.string.memberLogin1));
                        }
                    }
                    memberLoginGrade.setText(context.getResources().getString(R.string.memberLogin_grade) + infoBean.getGrade_name());
                    memberLoginIntegral.setText(context.getResources().getString(R.string.memberLogin_integral) + infoBean.getIntegral());
                    memberLoginMoney.setText(context.getResources().getString(R.string.memberLogin_money) + infoBean.getBalance());
                    Login_type = infoBean.getLogin_type();
                    payCode = infoBean.getPayCode();
                    discount = infoBean.getDiscount();
                    memberLoginAllPrice.setText("$" + (allPrice + zheKou));
                    /*if (vipinfoBean.getInfo().getDiscount() != null) {
                        if (Double.parseDouble(vipinfoBean.getInfo().getDiscount()) == 1) {
                            memberLoginZhekou.setText("無折扣");
                        } else {
                            double discount = Double.parseDouble(vipinfoBean.getInfo().getDiscount()) * 10;
                            memberLoginZhekou.setText(discount + "折");
                        }
                    }*/
                    memberLoginZheKou.setText(infoBean.getDiscount() + "");
                    memberLoginCoupon.setText("$" + zheKou);
                    memberLoginRealPay.setText("$" + decimalFormat.format(allPrice));
                    realPay = Double.parseDouble(decimalFormat.format(allPrice));
                    break;
                case 2:
                    loadingDialog.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_member_login);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.memberLoginTitle);
        allPrice = getIntent().getDoubleExtra("allPrice", 0);
        list = (List<GoodBean.DataBean.GoodsBean>) getIntent().getSerializableExtra("list");
        GetVipInfo();
        printUtil.getInstance().connectPrinterService(context);
    }

    @OnClick({R.id.vipLogin_close, R.id.vipLogin_sure, R.id.vipLogin_linear, R.id.title_back, R.id.memberLogin_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.vipLogin_close:
                vipLoginPass.setText("");
                vipLoginLinear.setVisibility(View.GONE);
                break;
            case R.id.vipLogin_sure:
                if ("".equals(vipLoginPass.getText().toString())) {
                    Toast.makeText(context, "會員密碼爲空", Toast.LENGTH_SHORT).show();
                    return;
                }
                VipPay();
                break;
            case R.id.vipLogin_linear:
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.memberLogin_sure:
                if (Login_type == 1) {
                    VipPay();
                } else {
                    vipLoginLinear.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void GetVipInfo() {
        infoBean = (VipListBean.InfoBean) getIntent().getSerializableExtra("vipinfoBean");
//        Toast.makeText(context, vipinfoBean.getMsg(), Toast.LENGTH_SHORT).show();
        Message msg = new Message();
        if (infoBean != null) {
            msg.what = 1;
        } else {
            msg.what = 2;
        }
        handler.sendMessage(msg);
    }

    private void VipPay() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        JSONArray goods = new JSONArray();
        try {
            for (int i = 0; i < list.size(); i++) {
                JSONObject good = new JSONObject();
                good.put("id", list.get(i).getId());
                good.put("retail_price", list.get(i).getRetail_price());
                good.put("goods_name", list.get(i).getGoods_name());
                good.put("good_image", list.get(i).getGoods_img());
                good.put("purch_price", list.get(i).getPurch_price());
                good.put("agood_count", list.get(i).getAgoods_count());
                good.put("num", list.get(i).getAgoods_count());
                good.put("vip_retail_state", list.get(i).getVip_retail_state());
                good.put("can_exchange_weigh", list.get(i).getPricing_method());
                good.put("canchangeprice", list.get(i).getPricing_method());
                good.put("attribute", list.get(i).getAttribute_state());
                good.put("store_mem_status", list.get(i).getStore_mem_status());
                good.put("store_mem_price", list.get(i).getStore_mem_price());
                if ("0".equals(list.get(i).getId())) {
                    good.put("goods_type", "2");
                } else {
                    good.put("goods_type", "1");
                }
                if ("2".equals(list.get(i).getAttribute_state()) && list.get(i).getSkujson() != null && list.get(i).getSkujson().size() > 0) {
                    JSONObject json = new JSONObject();
                    JSONArray jsarray = new JSONArray();
                    json.put("id", list.get(i).getSkujson().get(0).getId());
                    json.put("name", list.get(i).getSkujson().get(0).getSku());
                    json.put("sku_id_list", list.get(i).getSkujson().get(0).getSku_res());
                    json.put("retail_price", list.get(i).getSkujson().get(0).getRetail_price());
                    json.put("sku_num", list.get(i).getSkujson().get(0).getNum());
                    json.put("sku_code", list.get(i).getSkujson().get(0).getSku_code());
                    good.put("store_mem_status", list.get(i).getSkujson().get(0).getStore_mem_status());
                    good.put("store_mem_price", list.get(i).getSkujson().get(0).getStore_mem_price());
                    jsarray.put(json);
                    good.put("sku", jsarray);
                }
                goods.put(good);
            }
            jsonObject.put("uid", aCache.getAsString("uid"));
            jsonObject.put("payType", 5);
            jsonObject.put("adminId", aCache.getAsString("uid"));
            jsonObject.put("merchantId", aCache.getAsString("merchantid"));
            jsonObject.put("storeId", aCache.getAsString("storeid"));
            jsonObject.put("orderInfo", goods);
            jsonObject.put("discount", 1);
            jsonObject.put("cardCode", payCode);
            jsonObject.put("vipLoginType", Login_type);
            jsonObject.put("guideId", 0);
            jsonObject.put("changes_money", 0);
            jsonObject.put("couponId", 0);
            jsonObject.put("reducemoney", 0);
            jsonObject.put("vid", vipId);
            jsonObject.put("discount_money", zheKou);
            jsonObject.put("password", vipLoginPass.getText().toString());
            HttpUtils.post(context, Common.ORDER_PAY, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            vipLoginPass.setText("");
                            vipLoginLinear.setVisibility(View.GONE);
//                            printUtil.getInstance().print(list, infoBean.getDiscount()+"", "會員卡", allPrice);
                            intent = new Intent(context, PayCompleteActivity.class);
                            intent.putExtra("payflag", 2);//1,在線支付；2,會員支付；3,現金或其他
                            intent.putExtra("allPrice", realPay);
                            startActivity(intent);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
